package org.flexthinker.module.impl
{
    import mx.events.ModuleEvent;

    import org.flexunit.async.Async;
    import org.hamcrest.assertThat;
    import org.hamcrest.object.equalTo;

    public class DescriptorLoaderImplTest
    {
        //      to be used when tested from IDE
//        private static const MODULE_URL:String = "test-classes/test/ButtonModule.swf";

        //      to the used when tested with maven
        private static const MODULE_URL:String = "test/ButtonModule.swf";


        private var loader:DescriptorLoaderImpl;

        private var progressData:Array = [];

        public function DescriptorLoaderImplTest()
        {
        }

        [After]
        public function tearDown():void
        {
            loader = null;
        }

        [Test(async, timeout="4000")]
        public function testModuleLoadingWithProgress():void
        {
            loader = new DescriptorLoaderImpl(new ModuleDescriptor(MODULE_URL));
            loader.addEventListener(ModuleEvent.PROGRESS, progressHandler, false, 0, true);
            loader.addEventListener(ModuleEvent.ERROR, errorHandler, false, 0, true);
            Async.handleEvent(this, loader, ModuleEvent.READY, readyHandler, 4000);
            loader.load();
        }

        private function progressHandler(event:ModuleEvent):void
        {
            progressData.push({loaded:event.bytesLoaded, total:event.bytesTotal});
        }

        private function readyHandler(event:ModuleEvent, param:Object):void
        {
            assertThat("Module's ready flag should have been true", loader.ready, equalTo(true));
            testProgressData();
            loader.unload();
        }

        private function testProgressData():void
        {
            var i:int = 0;
            for (i = 1; i < progressData.length; i++)
            {
                assertThat("bytes loaded should be less than bytes total",
                        progressData[i].loaded <= progressData[i].total, equalTo(true));
                assertThat("progress went wrong", progressData[i - 1].loaded <= progressData[i].loaded, equalTo(true));

            }

            assertThat((progressData[i - 1].loaded - progressData[0].total) == 0, equalTo(true));
        }

        private function errorHandler(event:ModuleEvent):void
        {
            assertThat("module should have loaded", event.errorText, equalTo("Error is:"));
        }

    }
}